package com.atguigu.gulimall.cart.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;

import java.io.PrintWriter;

/**
 * 配置sentinel 错误的自定义返回数据
 */
@Configuration
public class SentinelConfig {
    public SentinelConfig() {
        WebCallbackManager.setUrlBlockHandler(
                (httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(JSON.toJSONString(
                            R.error(BizCodeEnume.TO_MANY_REQUEST)
                    ));
                }
        );
    }
}
